package chaoyue.study.juc;

import chaoyue.study.ThreadUtils;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch
 * 等待前面的线程执行完成之后才会继续后面的任务
 * 可以看到这边唤醒是会唤醒所有等待队列中的线程
 */
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        // 前置任务
        for (int i = 1; i <= 3; i++) {
            final int taskId = i;
            new Thread(() -> {
                ThreadUtils.sleepRandom();
                System.out.println("before task-" + taskId + " 执行完成");
                countDownLatch.countDown(); //countDown表示当前任务已经完成
            }).start();
        }

        // 后置任务
        for (int i = 1; i <= 3; i++) {
            final int taskId = i;
            new Thread(() -> {
                try {
                    countDownLatch.await();// 阻塞等待前值任务完成 才开始完成后续任务
                    System.out.println("after task-" + taskId + " 执行完成");
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
        System.out.println("main finish...");
    }
}
